<?php

namespace app\controller\Admin;

use think\Controller;
use think\facade\Db;
use think\facade\Request;
use app\validate\ClassicCaseArticle;

class ClassicCase extends Controller
{
    /**
     * 检查权限
     * @return bool
     */
    private function checkPermission()
    {
        // 这里简单返回 true，实际应根据用户登录状态和权限进行判断
        return true;
    }

    /**
     * 获取经典案例文章列表
     * @return \think\response\Json
     */
    public function getArticles()
    {
        if (!$this->checkPermission()) {
            return json(['code' => 403, 'msg' => '没有权限访问']);
        }
        try {
            $articles = Db::table('classic_case_articles')->select();
            return json($articles);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '数据库操作出错：' . $e->getMessage()]);
        }
    }

    /**
     * 保存经典案例文章
     * @return \think\response\Json
     */
    public function saveArticle()
    {
        if (!$this->checkPermission()) {
            return json(['code' => 403, 'msg' => '没有权限访问']);
        }
        $data = Request::post();
        $validate = new ClassicCaseArticle();
        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }
        try {
            $id = Db::table('classic_case_articles')->insertGetId($data);
            return json(['code' => 200, 'msg' => '保存成功', 'id' => $id]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '数据库操作出错：' . $e->getMessage()]);
        }
    }

    /**
     * 更新经典案例文章
     * @param int $id 文章 ID
     * @return \think\response\Json
     */
    public function updateArticle($id)
    {
        if (!$this->checkPermission()) {
            return json(['code' => 403, 'msg' => '没有权限访问']);
        }
        $data = Request::put();
        $validate = new ClassicCaseArticle();
        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }
        try {
            Db::table('classic_case_articles')->where('id', $id)->update($data);
            return json(['code' => 200, 'msg' => '更新成功']);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '数据库操作出错：' . $e->getMessage()]);
        }
    }

    /**
     * 删除经典案例文章
     * @param int $id 文章 ID
     * @return \think\response\Json
     */
    public function deleteArticle($id)
    {
        if (!$this->checkPermission()) {
            return json(['code' => 403, 'msg' => '没有权限访问']);
        }
        try {
            Db::table('classic_case_articles')->where('id', $id)->delete();
            return json(['code' => 200, 'msg' => '删除成功']);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '数据库操作出错：' . $e->getMessage()]);
        }
    }
}
